package teabag;

import java.util.ArrayList;

public class VariableManager {

		private static VariableManager instance;
		private static Math math;
		private static ArrayList<Variable> variableList;
	
		private VariableManager()
		{
			math = ScriptManager.math;
			variableList = new ArrayList<Variable>();
		}
		public static VariableManager getInstance()
		{
			if( instance == null )
				instance = new VariableManager();

			return instance;
		}
		public String toString()
		{
			String text = "Variables:\n";
			for( Variable v: variableList )
				text += v + "\n";
			return text;
		}
		protected String getValue( String name )
		{
			return getVariable( name ).getValue();
		}
		protected Type getType( String name )
		{
			return getVariable( name ).getType();
		}
		protected boolean removeVariable ( Variable v )
		{
			return variableList.remove( v );
		}
		protected Variable addVariable( String name, String value )
		{
			boolean bAdded = false;
			if( name.indexOf(' ') == -1 && getVariable(name) == null )
			{
				Type t = findType( value );
				Variable v = new Variable( name, t, value );
				bAdded = variableList.add( v );
				if( bAdded ) return v;
			}
			return null;
		}	

		protected void setValue( String name, String value )
		{
			int v = getVariableIx( name );
			//TODO: LOG Error
			if( v == -1 )
				return;
			Variable var = variableList.get(v);
			var.setValue(value);
			var.setType( findType( value ) );
			variableList.remove( v );
			variableList.add( var );
		}
		
		public Type findType( String value )
		{
			if( math._isInt( value ) ) 
				return Type.INTEGER;
			if( math._isDouble( value ) ) 
				return Type.DOUBLE;
			if( value.toLowerCase().equals("true") || value.toLowerCase().equals("false") )
				return Type.BOOLEAN;
			return Type.STRING;
		}
		
		protected boolean exists( String name )
		{
			return ( getVariable(name) != null);
		}
		
		protected Variable getVariable( String name )
		{
			for( Variable v : variableList )
				if( v.getName().equals(name) ) return v;
			return null;
		}
		
		private int getVariableIx( String name )
		{
			for( int i = 0; i < variableList.size(); i++ )
				if( variableList.get(i).getName().equals(name) ) return i;
			return -1;
		}
		
		class Variable
		{
			private String variableName;	
			private String stringValue;		
			private Type type;

			Variable( String name, Type t, String value )
			{
				type = t;
				variableName = name;
				stringValue = value;
			}
			public String toString()
			{
				String text = "";
				text = "Name: " + variableName + "\tValue: " + stringValue + "\tType: " + type;
				return text;
			}
			 
			public String getName(){ return variableName; }
			public Type getType(){ return type; }
			public String getValue(){ return stringValue; }
			
			public void setValue( String value ){ stringValue = value; }
			public void setType( Type iType ){ type = iType; }
		}
		

}


